package com.example.spring4.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Date;

@Aspect
@Component
public class UserInsertAspect {
    @Pointcut("execution(public * com.example.spring4.service..*.insertUser(..))")
    public void myFuncation(){

    }
    @Before("myFuncation()")
    public void beforeFun(JoinPoint joinPoint) throws IllegalAccessException {
        Object[] args=joinPoint.getArgs();
        for (Object arg:args) {
            Class aClass=arg.getClass();
            Field[] declaredFields = aClass.getDeclaredFields();
            for (Field field:declaredFields) {
                field.getName();
                field.setAccessible(true);
                if ("createBy".equals(field.getName())){
                    field.set(arg,"admin");
                }
                if ("createTime".equals(field.getName())){
                    field.set(arg,new Date());
                }

            }
        }
    }
    @After("myFuncation()")
    public void afterFun(){
        System.out.println("这是后置通知");
    }

}
